#include "./heat_task.h"
#include "../heat_driver/ctrl.h"
#include "../heat_driver/sensor.h"
#include "../cfg/heat_info.h"

namespace heat_task {

using namespace heat_driver;
using namespace cfg;

HeatTask heatTask;

void HeatTask::init_start() {
    m_mq.init();
    start();
}

void HeatTask::run() {

    for (;;) {
        switch (m_state) {
            case State::IDLE: do_idle(); break;
            case State::WORK: do_work(); break;
            case State::TIMEOUT: 
            case State::FAIL: do_timeout(); break;
            case State::STOP: do_stop(); break;
        }
    }
}

void HeatTask::do_idle() {

    for (;;) {
        if (sensor.is_hot_low()) {
            m_state = State::WORK;
            break;
        }

        if (wait(500)) {
            break;
        }
    }
}

void HeatTask::do_work() {

    uint32_t time_count = 0;
    for (;;) {
        if (!sensor.is_hot_low()) {
            m_state = State::IDLE;
            break;
        }

        if (sensor.water_temp() < heatInfo->hot_water_temp) {
            ctrl.open(Ctrl::Parts::WATER_HEAT);
            time_count += 500;
        } else {
            ctrl.close(Ctrl::Parts::WATER_HEAT);
            time_count = 0;
        }

        if (time_count >= heatInfo->hot_water_heat_time) {
            m_state = State::TIMEOUT;
            break;
        }

        if (wait(500)) {
            break;
        }
    }
    ctrl.close(Ctrl::Parts::WATER_HEAT);
}

void HeatTask::do_timeout() {
    wait();
}

void HeatTask::do_stop() {
    wait();
}

}
